﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JXT.PrimaryKey.Batman.Collections
{
    /// <summary>
    /// 延迟加载列表
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public class LazyList<T> : IList<T>
    {
        private Func<IList<T>> _listCreater;

        private IList<T> _innerList;
        protected virtual IList<T> InnerList
        {
            get
            {
                if (_innerList == null)
                {
                    _innerList = _listCreater();
                }
                return _innerList;
            }
        }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="list">实际列表</param>
        public LazyList(IList<T> list)
        {
            _listCreater = () => list;
        }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="creater">列表创建器</param>
        public LazyList(Func<IList<T>> creater)
        {
            _listCreater = creater;
        }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="creater">列表创建器</param>
        public LazyList(Func<IEnumerable<T>> creater)
        {
            _listCreater = () => creater().ToList();
        }

        public int IndexOf(T item)
        {
            return InnerList.IndexOf(item);
        }

        public void Insert(int index, T item)
        {
            InnerList.Insert(index, item);
        }

        public void RemoveAt(int index)
        {
            InnerList.RemoveAt(index);
        }

        public T this[int index]
        {
            get
            {
                return InnerList[index];
            }
            set
            {
                InnerList[index] = value;
            }
        }

        public void Add(T item)
        {
            InnerList.Add(item);
        }

        public void Clear()
        {
            InnerList.Clear();
        }

        public bool Contains(T item)
        {
            return InnerList.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            InnerList.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return InnerList.Count; }
        }

        public bool IsReadOnly
        {
            get { return InnerList.IsReadOnly; }
        }

        public bool Remove(T item)
        {
            return InnerList.Remove(item);
        }

        public IEnumerator<T> GetEnumerator()
        {
            return InnerList.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
